package com.wanxs.mall.product.controller;

import com.wanxs.mall.common.annotation.LogOperation;
import com.wanxs.mall.common.constant.Constant;
import com.wanxs.mall.common.page.PageData;
import com.wanxs.mall.common.utils.ExcelUtils;
import com.wanxs.mall.common.utils.PageUtils;
import com.wanxs.mall.common.utils.R;
import com.wanxs.mall.common.utils.Result;
import com.wanxs.mall.common.validator.AssertUtils;
import com.wanxs.mall.common.validator.ValidatorUtils;
import com.wanxs.mall.common.validator.group.AddGroup;
import com.wanxs.mall.common.validator.group.DefaultGroup;
import com.wanxs.mall.common.validator.group.UpdateGroup;
import com.wanxs.mall.product.dto.AttrGroupDTO;
import com.wanxs.mall.product.entity.AttrAttrgroupRelationEntity;
import com.wanxs.mall.product.entity.AttrEntity;
import com.wanxs.mall.product.entity.AttrGroupEntity;
import com.wanxs.mall.product.excel.AttrGroupExcel;
import com.wanxs.mall.product.service.AttrAttrgroupRelationService;
import com.wanxs.mall.product.service.AttrGroupService;
import com.wanxs.mall.product.service.AttrService;
import com.wanxs.mall.product.service.CategoryService;
import com.wanxs.mall.product.vo.AttrGroupRelationVO;
import com.wanxs.mall.product.vo.AttrGroupWithAttrsVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 属性分组
 *
 * @author wanxs 130001934@qq.com
 * @since 1.0.0 2023-09-01
 */
@RestController
@RequestMapping("product/attrgroup")
@Api(tags="属性分组")
public class AttrGroupController {
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrService attrService;
    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    @RequiresPermissions("product:attrgroup:page")
    public Result<PageData<AttrGroupDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<AttrGroupDTO> page = attrGroupService.page(params);

        return new Result<PageData<AttrGroupDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    @RequiresPermissions("product:attrgroup:info")
    public R get(@PathVariable("id") Long id){
        AttrGroupEntity attrGroupEntity = attrGroupService.getEntity(id);
        Long catelogId = attrGroupEntity.getCatelogId();
        Long[] paths = categoryService.queryCatelogPath(catelogId);
        attrGroupEntity.setCatelogPath( paths );
        return R.ok().put("attrGroup",attrGroupEntity);
    }

    @GetMapping("catelogPath/{catelogId}")
    @ApiOperation("信息")
//    @RequiresPermissions("product:attrgroup:info")
    public R getCatelogPath(@PathVariable("catelogId") Long catelogId){
        Long[] paths = categoryService.getCatelogPath(catelogId);
        return R.ok().put("paths",paths);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("product:attrgroup:save")
    public Result save(@RequestBody AttrGroupDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        attrGroupService.save(dto);

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    @RequiresPermissions("product:attrgroup:update")
    public Result update(@RequestBody AttrGroupDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        attrGroupService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("product:attrgroup:delete")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        attrGroupService.delete(ids);

        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    @RequiresPermissions("product:attrgroup:export")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<AttrGroupDTO> list = attrGroupService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, list, AttrGroupExcel.class);
    }


    @RequestMapping("/list/{catelogId}")
    //@RequiresPermissions("product:attrgroup:list")
    public R list( @PathVariable("catelogId") Long catelogId,@RequestParam Map<String, Object> params) {
        // PageUtils page = attrGroupService.queryPage(params);

        PageUtils page = attrGroupService.queryPage(params,catelogId);
        return R.ok().put("page", page);
    }

    @GetMapping("{attrGroupId}/attr/relation")
    public Result<List<AttrEntity>> getAttrRelation(@PathVariable("attrGroupId") Long attrGroupId){
        AttrGroupEntity attrGroupEntity = attrGroupService.getEntity(attrGroupId);

        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationService.queryAttryGroupRelation(attrGroupId);


        List<AttrEntity> collect = attrAttrgroupRelationEntities.stream().map(entity -> {
                    AttrEntity attrEntity = attrService.selectById(entity.getAttrId());
                    return attrEntity;
                }).filter((attrEntity) -> attrEntity != null)
                .collect(Collectors.toList());

        return new Result<List<AttrEntity>>().ok(collect);
    }



    @PostMapping("/attr/relation/delete")
    @ApiOperation("删除")
    @LogOperation("删除")
//    @RequiresPermissions("product:attrgroup:delete")
    public Result delete(@RequestBody List<AttrGroupRelationVO> attrGroupRelationVOS){
        //效验数据
        List<AttrAttrgroupRelationEntity> collect = attrGroupRelationVOS.stream().map(item -> {
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, entity);
            return entity;
        }).collect(Collectors.toList());
        attrGroupService.deleteRelation(collect);

        return new Result();
    }

    @PostMapping("/attr/relation")
    @ApiOperation("新增关联")
    @LogOperation("新增关联")
    //    @RequiresPermissions("product:attrgroup:addRelation")
    public Result addRelation(@RequestBody List<AttrGroupRelationVO> attrGroupRelationVOS){
        //效验数据

        attrAttrgroupRelationService.saveBatch(attrGroupRelationVOS);

        return new Result();
    }


    @RequestMapping("/{catelog_id}/withattr")
    @ApiOperation("新增关联")
    @LogOperation("新增关联")
    //    @RequiresPermissions("product:attrgroup:addRelation")
    public Result<List<AttrGroupWithAttrsVo>> withattr(@PathVariable("catelog_id")  Long catelog_id){
        //效验数据

        List<AttrGroupWithAttrsVo> vo = attrGroupService.withattr(catelog_id);

        return new Result().ok(vo);
    }


}